# coding=UTF-8
import paramiko, locale, warnings, os, time, logging, re,sys
from logging.handlers import RotatingFileHandler

sys_pre_encoding = locale.getpreferredencoding()
warnings.filterwarnings('ignore')


def loggerHandler(logdir, ip):
    start_time = time.strftime("%Y%m%d%H%M%S", time.gmtime())
    logfile = os.path.join(logdir, '{0}_{1}.log'.format(ip, start_time))

    # Gets or creates a logger
    # Define your own logger name
    logger = logging.getLogger(logfile)
    # Set default logging level to DEBUG
    logger.setLevel(logging.INFO)

    # create a console handler
    # and define a custom log format, set its log level to DEBUG
    print_format = logging.Formatter('%(levelname)-8s %(name)-12s %(message)s')
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(print_format)

    # create a log file handler
    rotating_log_format = logging.Formatter('[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s [in %(pathname)s:%(lineno)d]')
    rotating_file_handler = RotatingFileHandler(filename=logfile, maxBytes=1024, backupCount=3)
    rotating_file_handler.setLevel(logging.DEBUG)
    rotating_file_handler.setFormatter(rotating_log_format)

    #Add fille handlers to the logger
    logger.addHandler(rotating_file_handler)
    logger.addHandler(console_handler)
    return logger


class RemoteSSH:
    def __init__(self, logdir):
        self.logdir = logdir
        self.get_ip_list()
        self.ssh_session = None

    def __del__(self):
        if self.ssh_session is not None:
            self.ssh_session.close()
            self.ssh_session = None

    def get_ip_list(self):
        with open("sns.txt") as f:
            self.ip_list = [ip.split('\n')[0] for ip in f.readlines()]

    def send_cmd_by_ssh(self):
        client = paramiko.SSHClient()
        for ip in self.ip_list:
            logger = loggerHandler(self.logdir, ip)
            try:
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                username = 'ryan'
                password= '111111'
                client.connect(hostname=ip, username=username, password=password, port=22)
                self.ssh_session = client
                logger.info(f"Connecting to SSH on ip: {ip}, user: {username}, pwd: {password} ...")

                # channel = client.invoke_shell()
                # time.sleep(2)
                command = "pwd"
                msg = client.exec_command(command)
                if msg[2].read().decode(sys_pre_encoding) != '':
                    logger.error(f"Send {command} failed...")

                logger.info(f"{ip} send {command} success!")

            except Exception as err:
                logger.error(f"SSH Connect {ip} failed ... \n Error:{err}")

            finally:
                logger.info(f"Delete {ip} SSH session success ...")
                self.__del__()

if __name__ == '__main__':

    logdir = os.path.abspath('./logs')
    if not os.path.isdir(logdir):
        os.mkdir(logdir)
    else:
        for log in os.listdir(logdir):
            os.remove(f"{logdir}/{log}")

    rs = RemoteSSH(logdir)
    rs.send_cmd_by_ssh()